//
//  HJUserAccountViewModel.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/21.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

// 专门处理CZUserAccount的相关操作
class HJUserAccountViewModel: NSObject {
    
    static let sharedInstance: HJUserAccountViewModel = HJUserAccountViewModel()
    
    private override init() {
        super.init()
        // In a time account add sandbox in a single case, and assigned to userAccount
        userAccount = loadUserAccount()
    }
    // The user account, save AccessToken, after the procedure to use the HJUserAccount, have access to it (userAccount)
    var userAccount: HJUserAccount?
    
    // To determine whether the user is logged in
    var userLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    // 定义归档路径
//    var accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    private var accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    // The account information is save in the sandbox.
    private func saveUserAccount() -> Bool {
        if userAccount != nil {
            return NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }else {
            return false
        }
    }
    
    // Loading AccessToken and dictionary conversion model saved
    func loadAccessToken(code: String, completion: (error: NSError?) -> ()) {
        // api address
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // POST parameter
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        HJNetworkTool.sharedInstance.requestPOST(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                completion(error: error)
                return
            }
            // The dictionary turn model, and assigned to userAccount, for the external access
            self.userAccount = HJUserAccount(dict: result!)
            print("userAccount = \(self.userAccount)")
            // Save the model to the sandbox
            self.saveUserAccount()
            completion(error: nil)
        }
    }
    
    // Achieve user information
    func loadUserInfo(completion: (error: NSError?) ->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["uid": userAccount!.uid!]
        
        HJNetworkTool.sharedInstance.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                completion(error: error)
                return
            }
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            self.saveUserAccount()
            completion(error: nil)
        }
    }
    
    /**
    从沙盒里面加载用户账号
    returns: 之前保存的用户账号
    */
    private func loadUserAccount() -> HJUserAccount? {
        // 从沙盒里面解档账号
        NSLog("沙盒路径：%@",NSHomeDirectory());
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HJUserAccount
        // 解档并不一定能解档出
        // 判断账号是有在有效期内
////         TODO: 测试账号过期
//        account?.expiresDate = NSDate(timeIntervalSinceNow: -1000)
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("加载到有效的账号: \(account)")
            return account
        }
        
        return nil
    }
}
